package com.javaweb.system.config

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder


/**
 * 使用SpringSecurity
 * @author Siaze
 * @date 2021/12/10
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class WebSecurityConfig : WebSecurityConfigurerAdapter() {
    /**
     * 这个对象用于判断用户输入的账号密码是否存在
     * 用于登录
     */
    @Autowired
    lateinit var userDetailsService: UserDetailsService

    /**
     * 配置网站请求，哪些不需要拦截，登录跳转页面
     */
    override fun configure(http: HttpSecurity) {
        http.formLogin()
            .loginPage("/login")
                // 登录成功跳转页面
            .defaultSuccessUrl("/index")
            .and()
                //对请求授权
            .authorizeRequests()
                //不需要拦截的地址
            .antMatchers("/js/**", "/css/**","/login","/register").permitAll()
              //其他请求
            .anyRequest()
              //需要身份验证
            .authenticated()
            .and()
              //禁用跨站攻击
            .csrf().disable()
    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        // 设置登录判断
        auth.userDetailsService<UserDetailsService>(userDetailsService)
            //设置密码加密工具
            .passwordEncoder(BCryptPasswordEncoder())
    }

}


